<?php

namespace lico\Tool;

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment; // 容错率
use Endroid\QrCode\QrCode as EnQrCode;

class Qrcode
{

    protected $enQrCode;
    protected $config = [
        'encoding' => 'UTF-8', //编码类型
        'ext' => 'png', //图片后缀
        'size' => 300, //二维码大小
        'margin' => 20, //二维码内容相对于整张图片的外边距
        'foreground' => ['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0], //前景色
        'background' => ['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0], //背景色
        'title' => 'baidu', //二维码title bool/string

        'logo' => false, //STATIC_PATH.'image/test.jpg',//是否需要logo  bool/string
        'logo_width' => 80, //logo大小
    ];
    public function handler()
    {
        if (empty($this->enQrCode)) {
            $this->enQrCode = new EnQrCode();
        }
        return $this->enQrCode;
    }

    /**
     * 创建二维码
     */
    public function create($info)
    {

        $this->handler();
        // p($this->enQrCode);
        $this->enQrCode
            ->setText($info)
            ->setSize($this->config['size'])
            ->setWriterByName($this->config['ext'])
            ->setMargin($this->config['margin'])
            ->setEncoding($this->config['encoding'])
            ->setForegroundColor($this->config['foreground'])
            ->setBackgroundColor($this->config['background'])
            ->setErrorCorrectionLevel(new ErrorCorrectionLevel(ErrorCorrectionLevel::LOW));

        // 是否需要title
        if ($this->config['title']) {
            $this->enQrCode
                ->setLabel($this->config['title'], 16, null, LabelAlignment::CENTER);
        }
        // 是否需要logo
        if ($this->config['logo']) {
            $this->enQrCode
                ->setLogoPath($this->config['logo'])
                ->setLogoWidth($this->config['logo_width']);
        }

        $this->enQrCode->setValidateResult(false);

        return $this->enQrCode;
    }

    /**
     * 直接页面显示
     */
    public function view()
    {
        ob_end_clean();
        header('Content-Type: ' . $this->enQrCode->getContentType());
        echo $this->enQrCode->writeString();
        exit;
    }

    /**
     * 保存
     */
    public function save($path)
    {
        return $this->enQrCode->writeFile($path);
    }
}
